<template>
	<div class="main">
		<div style="width:50%;float:left">
			<div class="custom-styles">
				<span class="font14">{{type=='edit'?'编辑课程':'新增课程'}}</span>
			</div>
			<el-form ref="formRef" :model="form" label-width="80px">
				<div class="mc-item ct-item">
					<el-form-item label="课程名称" prop="name"
								  :rules="{required: true, message: '请输入课程名称', trigger: 'change'}">
						<el-input v-model="form.name" />
					</el-form-item>
					<el-form-item label="适用学段" prop="stage"
								  :rules="{required: true, message: '请选择适用学段', trigger: 'change'}">
						<el-select v-model="form.stage" @change="changeStage">
							<el-option v-for="item in options" :key="item.key" :label="item.value"
									   :value="item.key"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="适用年级" prop="grade" v-if="form.stage"
								  :rules="{required: true, message: '请选择适用学段', trigger: 'change'}">
						<el-select v-model="form.grade">
							<el-option v-for="item in gradeOptions" :key="item.key" :label="item.value"
									   :value="item.key"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="适用版本" prop="seriesNos" v-if="form.stage"
								  :rules="{required: true, message: '请选择适用版本', trigger: 'change'}">
						<el-select :disabled="type=='edit'?true:false" multiple v-model="form.seriesNos" @change="versionChange">
							<el-option v-for="item in versionOptions" :key="item.key" :label="item.value"
									   :value="item.key"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="适用册次" prop="semester"
								  :rules="{required: true, message: '请选择适用册次', trigger: 'change'}">
						<el-select v-model="form.semester">
							<el-option v-for="item in volumeOptions" :key="item.key" :label="item.value"
									   :value="item.key"></el-option>
						</el-select>
					</el-form-item>
					<div style="text-align:center;margin-top: 60px">
						<el-button type="primary" @click="saveForm">保 存</el-button>
					</div>
				</div>
			</el-form>
		</div>
		<div style="width:50%;float:left" v-if="type=='edit'">
			<el-collapse v-model="activeNames">
				<el-collapse-item title="章节管理" name="chapters">
					<el-button type="primary" link @click="addChapter" size="small" class="edit-course">+新增课程章</el-button>
					<div class="mc-item mc-item2">
						<tree
							:data="chapters.list"
							:courseNo="form.courseNo"
							tab="course"
							:maxLevel="3"
							@node-added="handleNodeAdded"
							@node-updated="handleNodeUpdated"
							@node-deleted="handleNodeDeleted"
							ref="treeRef"
						></tree>
					</div>
				</el-collapse-item>
			</el-collapse>
		</div>
	</div>
</template>
<script setup lang="ts">
import tree from '/#/tree/index.vue';
import { onMounted, reactive, ref, watch } from 'vue';
import { useRoute } from 'vue-router';
import { ElMessage, FormInstance } from 'element-plus';
import {
	getComboboxByStageId,
	getGradeCombobox,
	getSemesterCombobox,
	getSeriesCombobox,
	getStageCombobox
} from '/@/api/home/index';
import {
	getSeriesComboboxByStage,getSeriesTree,addCourse,modifyCourse, addCourseChapter,delCourseChapterById,modifyCourseChapter,
	getCourseChapterTreeByCourseNo
} from '/@/api/course/index';
import { useCool } from '/@/cool/hooks';
const route = useRoute();
const { router } = useCool();
const formRef = ref<FormInstance>();
let type = ref('');
let options = ref([]);
const treeRef = ref<InstanceType<typeof tree>>()
let gradeOptions = ref([]);//年级
let volumeOptions = ref([]);//册次
let versionOptions = ref([]);//版本
let seriesOptions = ref([]);//学科
let chapters = reactive({
	list: []
});
const activeNames = ref('chapters');
let form = reactive({
	id: '',
	courseNo: null,
	grade: '',
	stage: '',
	semester: '',
	orderNum: null,
	seriesNos: [] as any,
	name: ''
});

const queryTree = async () => {
	if (type.value === 'edit') {
		const parsedQuery = {
			...route.query,
			grade: Number(route.query.grade),
			stage: Number(route.query.stage),
			semester: Number(route.query.semester),
			seriesNos: [Number(route.query.seriesNo)]
		};

		//form = Object.assign({}, form, parsedQuery);
		Object.assign(form, parsedQuery)
		let treeList = await getCourseChapterTreeByCourseNo(form.courseNo);
		chapters.list = treeList.data;
	}
}
const addChapter = async () => {
	if (treeRef.value) {
		treeRef.value.appendRoot()
	}
};
const saveForm = () => {
	formRef.value?.validate(async valid => {
		if (valid) {
			let res = (type.value == 'add')? await addCourse(form) : await modifyCourse(form);
			if (res.code==200) {
				ElMessage.success((type.value == 'edit' ? '编辑课程' : '新增课程') + '成功');
				setTimeout(async () => {
					await router.push({
						path: '/course/list'
					})
				},500);
			}

		}
	});
};
watch(() => form.seriesNos, (newVal) => {
	if (newVal) {
		// 如果已经包含"通用版"，则不允许添加其他选项
		if (newVal.includes(200) && newVal.length > 1) {
			form.seriesNos = [200];
		}
	}

});
// 多选，选择了通用版则不能选择其它的选项
const versionChange = (val:any) => {
	if (val.includes(200)) {
		form.seriesNos = [200];
	}
}
onMounted(async () => {
	type.value = route.query.type;
	await queryTree();
	let res = await getStageCombobox();
	options.value = res.data;
	let res_ = await getGradeCombobox();
	gradeOptions.value = res_.data;
	let res__ = await getSeriesCombobox();
	versionOptions.value = res__.data;
	let res___ = await getSemesterCombobox();
	volumeOptions.value = res___.data;
	let res____ = await getSeriesTree();
	seriesOptions.value = res____.data;
});
const handleNodeAdded = async (newNode) => {
	let res = await addCourseChapter(newNode);
	if (res.code == 200) {
		newNode.id = res.data;
	} else {
		treeRef.value?.rollbackAddedNode()
	}
};
const handleNodeUpdated = async (node) => {	// 调用修改接口
	let res = await modifyCourseChapter(node);
	if (res.code !== 200) {
		treeRef.value?.rollbackNode();
	}
};
const changeStage = () => {
	form.grade = '';
	form.seriesNos = [];
	form.semester = '';
}
const handleNodeDeleted = async (id) => {
	await delCourseChapterById(id)
}
watch(() => form.stage, async (newVal) => {
	if (newVal) {
		let res = await getComboboxByStageId(newVal);
		gradeOptions.value = res.data;
		let res_ = await getSeriesComboboxByStage(newVal);
		versionOptions.value = res_.data;
	}
});
</script>
<style scoped lang="scss">

</style>
